package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AAentivity;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.LuckyRedEnvelopeEntivity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.PayString;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.GroupMemberAdpter;
import com.sam.im.heiqun.uis.beans.AATransDetailBean;
import com.sam.im.heiqun.uis.beans.queryLuckRedPacketEntivity;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.TimeUtil;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.image.CircleImageView;
import com.yuyh.library.view.text.PasswordEditText;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/12/25.
 */

public class LuckyRedEnvelopeActivity  extends BaseSwipeBackActivity {

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_discribe)
    TextView tvDiscribe;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.sure_bt)
    Button sureBt;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    @BindView(R.id.relative_title)
    RelativeLayout relative_title ;
    @BindView(R.id.aa_users)
    RecyclerView aa_users ;
    @BindView(R.id.txt_num)
    TextView txt_num ;
    ImMessage imMessage =null ;
    private int tag;
    private AlertDialog payDialog;
    PasswordEditText payPSD;
    private String amt;
    private String transId;
    private boolean payed;
    private static final String TAG = "AAActivity";
    public static final int REQUST_SENDTOFRIEND = 111;//发送消息给好友

    private GroupMemberAdpter mGroupMemberAdpter;
    private List<ImFriendEntivity> mFriendEntivities = new ArrayList<>();
    private double balance;
    //long receiptId;

    @Override
    public int getContentViewId() {
        return R.layout.activity_lucky_red_envelope;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.Luc_kyred_envelope);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor(R.color.red9));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        relative_title.setBackgroundColor(getResources().getColor(R.color.red9));
        imMessage = (ImMessage) getIntent().getSerializableExtra("data");
        Log.i(TAG, "initViews: ----" + imMessage.toString());
        tag = getIntent().getIntExtra("tag",0);
        String fromname = imMessage.getFromname();
        String imageIconUrl = imMessage.getImageIconUrl();
        String content = imMessage.getContent();

        Glide.with(this).load(imageIconUrl).centerCrop().into(imgIcon);

        tvName.setText(fromname+getResources().getString(R.string.Luc_kyred_envelope1));
        Long receiveTime = imMessage.getReceiveTime();
        //获取到当前时间做显示
        Calendar calendar=Calendar.getInstance();
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        tvTime.setText(+hour+":"+minute);
        payed = imMessage.isPayed();

        aa_users.setLayoutManager(new LinearLayoutManager(this, OrientationHelper.HORIZONTAL, false));
        mGroupMemberAdpter = new GroupMemberAdpter(this, 1);
        mGroupMemberAdpter.setItemClickListener(new GroupMemberAdpter.GroupMemberListClickListener() {
            @Override
            public void onGroupMemberListClick(View view, int position) {

            }
        });
        aa_users.setAdapter(mGroupMemberAdpter);
        mGroupMemberAdpter.refresh(mFriendEntivities);

        try {
            LuckyRedEnvelopeEntivity  LuckyRedEnvelope_ET= new Gson().fromJson(content, LuckyRedEnvelopeEntivity.class);
            amt = LuckyRedEnvelope_ET.getMoney();

            String msg = LuckyRedEnvelope_ET.getContent();

            transId = LuckyRedEnvelope_ET.getRedPacketId();
            Log.i(TAG, "initViews: ===============transId="+transId);

            tvMoney.setText(amt +getResources().getString(R.string.yuan));
            tvContent.setText(msg);
            //tvDiscribe.setText(counts+getResources().getString(R.string.ren_gong)+totalAmt+getResources().getString(R.string.yuan));
            getAADetails(imMessage.getFromid());
        }catch (Exception e){
            e.printStackTrace();
        }
        if (tag ==1){
            sureBt.setText(getResources().getString(R.string.call_friend));
        }else if (tag ==2){
//            if (payed){
//                sureBt.setText("已支付");
//                sureBt.setEnabled(false);
//                sureBt.setBackgroundResource(R.drawable.shape_sure_bt_false);
//            }else {
//                sureBt.setText("AA支付");
//            }
        }
    }

    @OnClick({R.id.pre_v_back, R.id.sure_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.sure_bt :
                if (tag==1){
//TODO 通知好友接口，等待提供
                    Intent intent = new Intent(LuckyRedEnvelopeActivity.this, SelecteLocalFriendActivity.class);
                    intent.putExtra("tag", 11);
                    intent.putExtra("msg", imMessage);
                    startActivityForResult(intent, REQUST_SENDTOFRIEND);
                }else if (tag==2){
                    final UserEntivity user = ToolsUtils.getUser();
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        //Toast.makeText(PayActivity.this, getString(R.string.please_set_pay_psd), Toast.LENGTH_SHORT).show();
                        showSetPSWdialog();
                        return;
                    }
                    showPayDialog();
                }
                break;
        }
    }
    private void showSetPSWdialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(LuckyRedEnvelopeActivity.this);
        builder.setTitle(getResources().getString(R.string.tip_psw));
        builder.setMessage(getResources().getString(R.string.no_pay_psw));
        builder.setNegativeButton(getResources().getString(R.string.now_no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton(getResources().getString(R.string.now_go), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(LuckyRedEnvelopeActivity.this, NewPasswordActivity.class);
                intent.putExtra("type", getResources().getString(R.string.set_pay_psd));
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        try {
            payDialog = new AlertDialog.Builder(this).setView(dialog).create();
            payDialog.show();
        }catch (Exception e){
            e.printStackTrace();
        }

        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                payDialog.dismiss();
            }
        });
        payCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    partakeLuckRed(pwd,imMessage.getFromid());
                    //  validatePayPwd(pwd);
                    payDialog.dismiss();
                }
            }
        });
    }

    private void popupKeyboard(final PasswordEditText editText) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    /**
     * 幸云红包 transfer/aaTransPay
     * amount 付款金额 string @mock=0.01
     destId 收款用户id string @mock=17229
     payPwd 支付密码 string @mock=sdsadsa
     transId 转账ID string @mock=2
     userId   dopaymoney
     *partakeLuckRed
     */

    private void partakeLuckRed(String psw, final long receiptId) {
        showProgress(getResources().getString(R.string.commit_now));
        String payPsd = MD5.MD532(psw);
        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        String destid1=Long.toString(receiptId);//把destid强转成string类型
        PGService.getInstance().partakeLuckRedPacket(userId,transId,destid1).subscribe(new AbsAPICallback<ValidateEntivity>() {
            // PGService.getInstance().aaTransPay(amt, receiptId+"", payPsd, transId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {

                Log.i(TAG, "onResultError: ------ex.getCode()----"+ex.getCode());
                if (ex != null) {

                    try {

                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(ex.getDisplayMessage());
                        com.alibaba.fastjson.JSONObject data = object.getJSONObject("data");

                        showToast(data.getString("info"));
                        finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

//
                   /* if (-1 == ex.getCode()){
                        ToolsUtils.showToast(LuckyRedEnvelopeActivity.this, getResources().getString(R.string.pay_psw_error));
                    }
                    if (3 == ex.getCode()){
                        ToolsUtils.showToast(LuckyRedEnvelopeActivity.this, getResources().getString(R.string.no_money));
                    }*/
                }
                hideProgress();
            }
            @Override
            public void onNext(ValidateEntivity validateEntivity) {//这里支付成功后不做发送消息处理
                if (validateEntivity != null) {
                    ToolsUtils.showToast(LuckyRedEnvelopeActivity.this, validateEntivity.getInfo());
                    JSONObject obj = new JSONObject();
                    try {
                        obj.put("amt",amt+"");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final ImMessage immsg = getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_PAYFOR, UUID.randomUUID().toString(), Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_SYS,receiptId,obj.toString(), Constant.MESSAGE_TYPR_TOPAYFOR,
                            System.currentTimeMillis(), System.currentTimeMillis(), 0, null, ToolsUtils.getMyUserId() + "___", 0, imMessage.getImageIconUrl());
                    immsg.save();
                    MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(immsg, Constant.FROM_TYPE_OTHER);
                    EventBus.getDefault().post(new PayString(imMessage.getMsgId()));
                    EventBus.getDefault().post(messageEntivity);
                    hideProgress();
                    finish();
                } else {
                    ToolsUtils.showToast(LuckyRedEnvelopeActivity.this, getResources().getString(R.string.pay_fail));
                }
                hideProgress();//RecordVideo
            }
        });
    }
    //生成消息对象
    public ImMessage getTbub(int version, int devType, int geoId, int type,
                             String msgId, long fromId, int fromType,
                             long destId, String content, int messageType,
                             long sendTime, long receiveTime, int status, String filePath, String uniqueness, float seconds, String imageIconUrl) {
        ImMessage tbub = new ImMessage();
        tbub.setVersion(version);
        tbub.setDevType(devType);
        tbub.setUserVoiceTime(seconds);
        tbub.setType(type);
        tbub.setGeoId(geoId);
        tbub.setMsgId(msgId);
        tbub.setFromid(fromId);
        tbub.setFromType(fromType);
        //tbub.setFileUrl(content);
        tbub.setFilePath(filePath);
        //tbub.setUserVoicePath(content);
        tbub.setDestid(destId);
        if (content.equals("null")){
            content = "null ";
        }
        tbub.setContent(content);
        tbub.setMessageType(messageType);
        tbub.setFromname(ToolsUtils.getUser().getNickName());//设置名字
        tbub.setSendTime(sendTime);
        tbub.setReceiveTime(receiveTime);
        tbub.setStatus(status);
        tbub.setUniqueness(uniqueness);
        tbub.setSendState(Constant.SENDING);
        tbub.setImageIconUrl(imageIconUrl);
        // tbub.save();
        //  ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
        //  IMMessageToJson.ImMessageToMessageEntivity(tbub, Constant.FROM_TYPE_SELF);
        return tbub;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUST_SENDTOFRIEND:
                if (resultCode == REQUST_SENDTOFRIEND) {
                    scrollToFinishActivity();
                }
                break;
        }
    }

    /**
     *
     */
    private void getAADetails(final long receiptId) {
        String userId=ToolsUtils.getMyUserId();
        String destid1=Long.toString(receiptId);
        //showProgress(getResources().getString(R.string.now_down));
        PGService.getInstance().queryLuckRedPacket(userId,transId,destid1).subscribe(new AbsAPICallback<queryLuckRedPacketEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {

               // hideProgress();
            }
            @Override
            public void onNext(queryLuckRedPacketEntivity queryluckredpacketentivity) {//
                if (null!=queryluckredpacketentivity && null!=queryluckredpacketentivity.getLuckCount()){
                    if (queryluckredpacketentivity.getIsReceive().equals("false")&&!queryluckredpacketentivity.getIsEffect().equals("false")) {
                        sureBt.setText(getResources().getString(R.string.to_participate_in));
                        sureBt.setEnabled(true);
                        sureBt.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                    }else {
                        sureBt.setText(getResources().getString(R.string.already_involved_bt));
                        sureBt.setEnabled(false);
                        sureBt.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    }
                    if (queryluckredpacketentivity.getIsEffect().equals("false")){
                        sureBt.setText(getResources().getString(R.string.baidu_translate));
                        sureBt.setEnabled(false);
                        sureBt.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    }
                    balance = Double.parseDouble(queryluckredpacketentivity.getBalance());
                    tvBalance.setText(LuckyRedEnvelopeActivity.this.getResources().getString(R.string.yu_e_1)+queryluckredpacketentivity.getBalance()+LuckyRedEnvelopeActivity.this.getResources().getString(R.string.yuan));
                    txt_num.setText(LuckyRedEnvelopeActivity.this.getResources().getString(R.string.Already_existing)+queryluckredpacketentivity.getLuckCount()+LuckyRedEnvelopeActivity.this.getResources().getString(R.string.participate_in));
                }
            }
        });
    }

}
